package org.sczfdf.utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.SystemClock;
import org.sczfdf.conf.MailConf;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author Created by cgb
 * @date 2023/1/31
 */
public class MailUtil {
    public static final Session SESSION = Session.getDefaultInstance(new Properties());
    public static final MailConf MAIL_CONF = MailConf.get();

    private static final Integer SEND_INTERVAL = MAIL_CONF.getSendInterval();

    private static volatile long sync = 0;

    private static boolean checkInterval() {
        LogUtil.logInfo("mail checkInterval " + sync);
        long now = SystemClock.now();

        if (sync + SEND_INTERVAL * DateUnit.MINUTE.getMillis() < now) {
            sync = now;
            return false;
        }else {
            return true;
        }
    }


    public static void sendMail(String msg) {
        if (checkInterval()) {
            return;
        }

        try {
            // 不知道为什么按网上的来不行, 会报553 authentication is required
            MimeMessage message = new MimeMessage(SESSION);

            // 设置发件人
            InternetAddress from = new InternetAddress(MAIL_CONF.getSendMailAccount());
            message.setFrom(from);

            // 设置收件人
            InternetAddress to = new InternetAddress(MAIL_CONF.getReceiveMailAccount());
            message.setRecipient(Message.RecipientType.TO, to);

            //设置邮件主题
            message.setSubject("主题");

            //设置邮件内容
            message.setContent(msg, "text/html;charset=utf-8");

            //保存上面设置的邮件内容
            message.saveChanges();

            Transport transport = SESSION.getTransport();
            transport.connect(MAIL_CONF.getSmtpHost(), MAIL_CONF.getSmtpPort(), MAIL_CONF.getSendMailAccount(), MAIL_CONF.getSendMailAuth());
            //发送邮件
            transport.sendMessage(message, message.getAllRecipients());
        } catch (MessagingException e) {
            LogUtil.logError("发送邮件失败");
            throw new RuntimeException(e);
        }

    }
}

